package com.garlic.face.jlf.presenter;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.garlic.face.jlf.App;
import com.garlic.face.jlf.R;
import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.transaction.ServiceInterface;
import com.garlic.face.jlf.transaction.balance.cclhelper.GoodsHelper;
import com.garlic.face.jlf.transaction.balance.cclhelper.TradeHelper;
import com.garlic.face.jlf.transaction.balance.database.GoodsWeight;
import com.garlic.face.jlf.transaction.balance.database.ItemExceptions;
import com.garlic.face.jlf.transaction.balance.greendao.gen.GoodsWeightDao;
import com.garlic.face.jlf.transaction.balance.greendao.gen.ItemExceptionsDao;
import com.garlic.face.jlf.transaction.bean.SaleFlow;
import com.garlic.face.jlf.transaction.constances.JLFConstant;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.ToastUtils;
import com.garlic.face.jlf.utils.Tools;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @author wenhui02.liu
 * @date 2018/8/10.
 */

public class ScanGoodsPresenter implements ScanGoodsContract.Presenter {

    ScanGoodsContract.View mView;
    private static String TAG = "ScanGoodsPresenter";
    private List<SaleFlow> mItemList = new ArrayList<>();
    private int reduceItemCount = 0;
    private int addItemCount = 0;
    private int reduceOrDelete = -1;//记录是否删除或-1

    String mBarcode;//当前条码

    boolean changePosition = true;//+-不改变列表商品位置

    private boolean isVerify = false;//true--正在比较商品重量
    boolean isWeighting = false;//重量提示框是否显示
    boolean isCancelling = false;//true--正在进行取消商品的判断
    private Handler handler;
    GoodsWeightDao mGoodsWeightDao;
    ItemExceptionsDao mItemExceptionsDao;
    private ExecutorService executorService;

    public ScanGoodsPresenter(ScanGoodsContract.View view) {
        mView = view;
        mGoodsWeightDao = App.getInstances().getDaoSession().getGoodsWeightDao();
        mItemExceptionsDao = App.getInstances().getDaoSession().getItemExceptionsDao();
        executorService = Executors.newCachedThreadPool();
    }

    public void openExecutorService(){
        if(executorService == null || executorService.isShutdown()){
            executorService = Executors.newCachedThreadPool();
        }
    }

    /**
     * 网络端取消交易
     */
    @Override
    public void cancelTransaction() {
        ServiceInterface.getInstance().cancelTrade("", "");
    }

    public boolean getIsVerify(){
        return isVerify;
    }

    public boolean getIsCancelling(){
        return isCancelling;
    }

    /**
     * 获取商品是否合法，计算总价
     *
     * @param barCode 条码
     * @param qty     数量
     */
    @Override
    public void getItemInfo(final String barCode, final String qty) {
        ArrayList<SaleFlow> goodsList = Means.getInstance().getItemHead();
        for(SaleFlow item : goodsList){
            if(item.getBarcode().equals(barCode) && item.getPlutype().equals("1") && !(item.getWeightPluType() == 2)){
                ToastUtils.toastShow("同件称重商品不可重复扫码", ToastUtils.ERROR);
                return;
            }
        }
        Log.e(TAG, "xxxx barCode:" + barCode);
        mView.showProgress();
        mBarcode = barCode;
        addItemCount = Integer.valueOf(qty);
        ServiceInterface.getInstance().getGoodsInfo(mBarcode, qty);
    }

    /**
     * 支付前最终的网络商品校验
     */
    @Override
    public void calcItemPriceEnd() {
        mView.showProgress();
        ServiceInterface.getInstance().getSubtotal();
    }

    @Override
    public void addItem(int position) {
        changePosition = false;
        SaleFlow selectItem = getItemList().get(position);

        String barCode = selectItem.getBarcode();
        getItemInfo(barCode, "1");
    }

    @Override
    public void reduceItem(int position) {
        changePosition = false;
        reduceOrDelete = 1;
        Means.getInstance().setPosition(position);
        final SaleFlow saleFlow = getItemList().get(position);
        reduceItemCount = saleFlow.getCount() - 1;
        ServiceInterface.getInstance().removeBarcode("", "", saleFlow.getBarcode(), "1");
    }

    @Override
    public void reduceItem(int position, int count) {
        changePosition = false;
        reduceOrDelete = 1;
        Means.getInstance().setPosition(position);
        final SaleFlow saleFlow = getItemList().get(position);
        reduceItemCount = saleFlow.getCount() - count;
        ServiceInterface.getInstance().removeBarcode("", "", saleFlow.getBarcode(), String.valueOf(count));
    }

    @Override
    public void removeItem(int position) {
        reduceOrDelete = 0;
        Means.getInstance().setPosition(position);
        //取消单品不需要送supervisor
        final SaleFlow saleFlow = getItemList().get(position);
        reduceItemCount = 0;
        ServiceInterface.getInstance().removeBarcode("", "", saleFlow.getBarcode(), String.valueOf(saleFlow.getCount()));
    }

    @Override
    public void getMemberInfo(String barCode) {
        mView.showProgress();
        Log.e(TAG, barCode);
        final String vipNumber = barCode;
        ServiceInterface.getInstance().getVipNumber(vipNumber);
    }

    /**
     * 收银员登录
     */
    private void cashierLogin(String cashier, String cashierPwd) {
        ServiceInterface.getInstance().cashierLogin(cashier, cashierPwd);
    }

    /**
     * 设置全局金额、数量
     */
    private void setTotalData() {
        ArrayList<SaleFlow> goodlist = Means.getInstance().getItemHead();
        Double totalPrice = 0.00;
        Double totalNumber = 0.00;
        Double totalCount = 0.00;
        Double totalWeight = 0.00;
        for (int i = 0; i < goodlist.size(); i++) {
            SaleFlow saleFlow = goodlist.get(i);
//            totalPrice += (saleFlow.getAmount() * saleFlow.getQty());
            if (saleFlow.getPlutype().equals("0")) {
                totalNumber += saleFlow.getCount();
            }else{
                if (saleFlow.getWeightPluType() == 2){
                    Log.e("*--------*****", saleFlow.getCount()+"");
                    Log.e("*--------*****", saleFlow.getQty()+"");
                    totalNumber += saleFlow.getCount()*saleFlow.getQty();
                }else{
                    totalNumber += saleFlow.getQty()*saleFlow.getCount();
                }
            }
            LogUtils.d("xxxxx total: totalNumber" + totalNumber + "  saleFlow.getQty():" + saleFlow.getQty() + "-------salefow weight" + saleFlow.getWeight(), true);
            totalWeight += saleFlow.getWeight()* saleFlow.getCount();
//            if (saleFlow.getPlutype().equals("1")) {
//                totalCount += ;
//                totalPrice += saleFlow.getAmount();
//            } else {
                totalCount += saleFlow.getCount();
                totalPrice += (saleFlow.getPrice() * saleFlow.getCount());
//            }
        }
        Means.getInstance().getRec_Tran().setAmount(totalPrice);
        Means.getInstance().getRec_Tran().setQty(totalNumber);
        Means.getInstance().getRec_Tran().setCount(totalCount);
        Means.getInstance().getRec_Tran().setWeight(totalWeight);
        LogUtils.d("xxxxx total:" + Means.getInstance().getRec_Tran(), true);
    }

    /**
     * 更新扫描出来的商品到列表顶部，并计算数量是否需要累加
     *
     * @param saleFlow
     */
    private void calcItemList(final SaleFlow saleFlow) {
        //把新扫描到的商品添加到缓存的商品列表中..
        //非承重的逻辑
        LogUtils.d("xxxxx  saleFlow:" + saleFlow, true);
        int index = -1;
        for (int i = 0; i < getItemList().size(); i++) {
            SaleFlow x = getItemList().get(i);
            LogUtils.d("计算每个商品的重量是:每个商品的内容:"+x.toString(), false);
            //手动输入的条码没有开头字母，扫描的带开头字母，这里去除开头字母后匹配
            if (x.getBarcode().replaceAll("^[a-zA-Z]", "").equals(saleFlow.getBarcode().replaceAll("^[a-zA-Z]", ""))) {
                index = i;
                break;
            }
        }

        if (index == -1) {
            //不存在相同的商品..加到顶部
            getItemList().add(0, saleFlow);
        } else {
            //存在相同的商品..
            SaleFlow x = getItemList().get(index);
            //这个不知道加了干啥的...
//            double count = x.getQty();
//            //设置进去
//            saleFlow.setQty(count);
            int pos = index;
            if (changePosition) {
                pos = 0;
            }
            saleFlow.setCount(x.getCount() + addItemCount);
            addItemCount = 0;
            getItemList().remove(index);
            //归位到顶部
            getItemList().add(pos, saleFlow);
            LogUtils.d(TAG + JSON.toJSONString(getItemList()), true);
            changePosition = true;
        }

    }

    public List<SaleFlow> getItemList() {
        return Means.getInstance().getItemHead();
    }

    @Override
    public void parseResponse(JSONObject jsonObject) {
        try {
            String interfaceType = jsonObject.getString("INTERFACETYPE");
            String retflag = jsonObject.getString("retflag");
            String retmsg = jsonObject.getString("retmsg");

            if (interfaceType.equals(JLFConstant.TAG_GOOD_RESPONSE)) {
                mView.hideLoad();
                mView.hideProgress();
                if (retflag.equals("0")) {
                    //TODO: 区分称重和普通。。普通的花。qty＝当前增加的数量。 称重的花。默认是1.
                    SaleFlow saleFlow = new SaleFlow();
                    saleFlow.setBarcode(mBarcode);
                    fillSaleFlow(saleFlow, jsonObject);
                    int count = Means.getInstance().getItemCount();
                    Means.getInstance().setItemCount(count + 1);

                    for(int i =0; i< Means.getInstance().getItemHead().size(); i++){
                        Means.getInstance().getItemHead().get(i).setHighlight(false);
                    }
                    saleFlow.setHighlight(true);
                    calcItemList(saleFlow);//合并或添加商品
                    setTotalData();
                    //mView.showItemDialog(true, saleFlow, Means.getInstance().getRec_Tran());

                    LogUtils.d("saleflow plutype" + saleFlow.getPlutype() + "qty:"+ jsonObject.getDouble("qtysold") + "saleflow qty:"+saleFlow.getQty(), true);

                    if(!Means.blAssistMode){
                        if (saleFlow.getPlutype().equals("0")) {
                            scanPluVerify(saleFlow, jsonObject.getDouble("qtysold"));
                        } else {
                            if (saleFlow.getWeightPluType() == 2) {
                                scanPluVerify(saleFlow, jsonObject.getDouble("qtysold"));
                            } else {
                                scanPluVerify(saleFlow, 1);
                            }
                        }
                    }
                    mView.processItemList(Means.getInstance().getRec_Tran());
//                    mView.setCurrentSaleFlow(saleFlow);
                } else {
                    ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
                    LogUtils.e("添加商品" + retmsg);
                }
            } else if (interfaceType.equals(JLFConstant.TAG_CANCELGOOD_RESPONSE)) {
                mView.hideLoad();
                mView.hideProgress();
//                mView.setCurrentSaleFlow(Means.getInstance().getItemHead().get(Means.getInstance().getPosition()));
                if (retflag.equals("0")) {
                    if (reduceOrDelete == 0) {
                        for(int i =0; i< Means.getInstance().getItemHead().size(); i++){
                            Means.getInstance().getItemHead().get(i).setHighlight(false);
                        }
                        Means.getInstance().getItemHead().remove(Means.getInstance().getPosition());
                    } else if (reduceOrDelete == 1) {
                        SaleFlow saleFlow = Means.getInstance().getItemHead().get(Means.getInstance().getPosition());
                        //没意义
//                        double count = saleFlow.getQty();
//                        count = count - 1;
//                        saleFlow.setQty(count);
                        LogUtils.d("cancel goods" + reduceItemCount, true);
                        saleFlow.setCount(reduceItemCount);
                        for(int i =0; i< Means.getInstance().getItemHead().size(); i++){
                            Means.getInstance().getItemHead().get(i).setHighlight(false);
                            LogUtils.d("每个商品的信息是:"+Means.getInstance().getItemHead().get(i).toString(), true);
                        }
                        saleFlow.setHighlight(true);
                        reduceItemCount = 0;
                    }
                    setTotalData();
                    if(!Means.blAssistMode){
                        setTotalWeight();
                    }
                    mView.processItemList(Means.getInstance().getRec_Tran());
                } else {
                    ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
                    LogUtils.e("取消商品" + retmsg);
                }
                reduceOrDelete = -1;
            } else if (interfaceType.equals(JLFConstant.TAG_CANCELTRADE_RESPONSE)) {
                mView.hideLoad();
                mView.hideProgress();
                if (retflag.equals("0")) {
                    Tools.clearTrade();
                    if(!Means.blAssistMode) {
                        setTotalWeight();
                    }
                    mView.processItemList(Means.getInstance().getRec_Tran());
                    mView.gotoMain();
                    mView.hideSuperVisorDlg();
                } else {
                    ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
                    LogUtils.e("取消交易" + retmsg);
                }
            } else if (interfaceType.equals(JLFConstant.TAG_SUBTOTAL_RESPONSE)) {
                mView.hideLoad();
                mView.hideProgress();
                if (null != retflag && retflag.equals("0")) {
                    Double total = jsonObject.getDouble("subtotal");
                    Double dis_amount = jsonObject.getDouble("clsreward");
                    String transnmbr = jsonObject.getString("transnmbr");
                    Means.getInstance().getRec_Tran().setAmount(total);
//                    Means.getInstance().getRec_Tran().setRemian(total);
                    Means.getInstance().getRec_Tran().setDisc_amt(dis_amount);
                    Means.getInstance().getRec_Tran().setTransnmbr(transnmbr);
                    mView.gotoPay();
                } else {
                    ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
                    LogUtils.e("计价错误" + retmsg);
                }
            } else if (interfaceType.equals(JLFConstant.TAG_VIP_RESPONSE)) {
                mView.hideLoad();
                mView.hideProgress();
                if (retflag.equals("0")) {
                    String cardnumber = jsonObject.getString("cardnumber");
                    String points = jsonObject.getString("points");
                    Means.getInstance().getRec_Tran().setCustcode(cardnumber);
                    Means.getInstance().getRec_Tran().setPoints(points);
                    ToastUtils.toastShow(App.getContext().getResources().getString(R.string
                            .vip_login_success), ToastUtils.SUCCESS);
                    mView.refreshVipTextView(cardnumber, points);
                } else {
                    ToastUtils.toastShow(App.getContext().getResources().getString(R.string
                            .vip_login_failed) + ":" + retmsg, ToastUtils.SUCCESS);
                    LogUtils.e("会员登录失败" + retmsg);
                }
            } else if (interfaceType.equals(JLFConstant.TAG_SUPERVISOR_RESPONSE)) {
                mView.hideProgress();
                retflag = jsonObject.getString("retflag");
                retmsg = jsonObject.getString("retmsg");
                if (retflag.equals("0")) {

                    mView.hideSuperVisorDlg();

                    mView.confirmGoods();

//                    mView.showNormalDlog();

                } else {

                    mView.setSuperVisorPwd("");
                    ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setTotalWeight() {
        Means.blApproveWeight = false;
        isCancelling = true;
        double weight = 0;
        for (int i = 0; i < Means.getInstance().getItemHead().size(); i++){
            SaleFlow item = Means.getInstance().getItemHead().get(i);
            if (item.getPlutype().equals("0")){
                weight += item.getWeight() * item.getCount();
            }else{
                if(item.getWeightPluType() == 2){
                    LogUtils.e("getWeightPluType-2:" + item.getWeight() + "-" + item.getCount() + "-" + item.getQty());
                    weight += item.getWeight()*item.getCount()*item.getQty();
                }else {
                    LogUtils.e("getWeightPluType-1:" + item.getWeight() + "-" + item.getCount() + "-" + item.getQty());
                    weight += item.getWeight() * item.getCount();
                }
            }
            LogUtils.d("-------1*" +  item.getCount(), false);
        }
        LogUtils.d("-------2*" + weight, false);
        weight = BigDecimal.valueOf(weight).add(BigDecimal.valueOf(Means.BagWeight)).doubleValue();
        double finalWeight = weight;
        LogUtils.d("-------finalWeight" + finalWeight, false);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (isCancelling) {
                    try {
                        Thread.sleep(50);
                        //重量没变化
                        if(Means.weightqty == Means.TotalWeight){
                            Thread.sleep(500);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (Means.blApproveWeight) {
                        isCancelling = false;
                        Means.TotalWeight = Means.weightqty;
                        Message message = Message.obtain();
                        message.what = 3;
                        handler.sendMessage(message);
                        break;
                    } else {
                        LogUtils.e("------cancel" + Means.weightqty +" "+finalWeight+" "+Means.InitWeight+" "+Means.ToleranceNoScan+" "+Means.blAssistMode);
                        if ((Means.weightqty >= BigDecimal.valueOf(finalWeight).add(BigDecimal.valueOf(Means.InitWeight)).subtract(BigDecimal.valueOf(Means.ToleranceNoScan)).doubleValue()
                                && Means.weightqty <= BigDecimal.valueOf(finalWeight).add(BigDecimal.valueOf(Means.InitWeight)).add(BigDecimal.valueOf(Means.ToleranceNoScan)).doubleValue())
                                || Means.weightqty <= Means.InitWeight
                                || Means.blAssistMode)
                        {
                            Message message = Message.obtain();
                            message.what = 4;
                            handler.sendMessage(message);
                            Means.TotalWeight = Means.weightqty;
                            isCancelling = false;
                            break;
                        }
                        else if(Means.weightqty > BigDecimal.valueOf(finalWeight).add(BigDecimal.valueOf(Means.InitWeight)).add(BigDecimal.valueOf(Means.ToleranceNoScan)).doubleValue()){
                            //"请检查您的购物袋，并将已取消的商品从装袋台上移开"
                            LogUtils.i("run: isWeighting:" + isWeighting, false);
                            if(!isWeighting){
                                Message message = Message.obtain();
                                message.what = 1;
                                message.obj = JLFConstant.WEIGHT_CANCEL_OVER;
                                handler.sendMessage(message);
                            }
                            else {
                                Message message = Message.obtain();
                                message.what = 2;
                                message.obj = JLFConstant.WEIGHT_CANCEL_OVER;
                                handler.sendMessage(message);
                                LogUtils.i("run: message.what = 2;", false);
                            }
                        }
                        else{
                            //请检查您的购物袋，把未取消的商品放回装袋台，然后按“确认”按钮。
                            if(!isWeighting){
                                Message message = Message.obtain();
                                message.what = 1;
                                message.obj = JLFConstant.WEIGHT_CANCEL_LOW;
                                handler.sendMessage(message);
                            }
                            else{
                                Message message = Message.obtain();
                                message.what = 2;
                                message.obj = JLFConstant.WEIGHT_CANCEL_LOW;
                                handler.sendMessage(message);
                            }
                        }
                    }
                }
            }
        };
        executorService.execute(runnable);
    }
    @Override
    public void weight(String weight) {
        if (Means.blAssistMode || !Means.blScaleOK) {
            return;
        }
        Means.weightqty = Double.parseDouble(weight);
        LogUtils.d("------weight" + Means.weightqty +"--"+Means.TotalWeight+"--" +Means.ToleranceNoScan + "------isVerify" + isVerify + "-----isCancelling" + isCancelling, false);

        if (!isVerify && !isCancelling) {
            if (Means.weightqty < BigDecimal.valueOf(Means.TotalWeight).subtract(BigDecimal.valueOf(Means.ToleranceNoScan)).doubleValue()) {
                //blScaleEvent = false;
                Means.blApproveWeight = false;
                if (!isWeighting) {
                    Message message = Message.obtain();
                    message.what = 1;
                    message.obj = JLFConstant.WEIGHT_BAG_DLG;
                    handler.sendMessage(message);
                } else {
                    Message message = Message.obtain();
                    message.what = 2;
                    message.obj = JLFConstant.WEIGHT_BAG_DLG;
                    handler.sendMessage(message);
                }

            } else if (Means.weightqty > BigDecimal.valueOf(Means.TotalWeight).add(BigDecimal.valueOf(Means.ToleranceNoScan)).doubleValue()) {
                //blScaleEvent = false;
                Means.blApproveWeight = false;
                if (!isWeighting) {
                    Message message = Message.obtain();
                    message.what = 1;
                    message.obj = JLFConstant.WEIGHT_UNEXCEPTED_DLG;
                    handler.sendMessage(message);
                } else {
                    Message message = Message.obtain();
                    message.what = 2;
                    message.obj = JLFConstant.WEIGHT_UNEXCEPTED_DLG;
                    handler.sendMessage(message);
                    //weightDialog.setContent(JLFConstant.WEIGHT_UNEXCEPTED_DLG);
                }
            } else {
                mView.setBlscaleEvent(true);
                Message message = Message.obtain();
                message.what = 4;
                handler.sendMessage(message);
            }
        }
    }

    @Override
    public void setWeightHandler(Handler weightHandler) {
            handler = weightHandler;
    }

    private void fillSaleFlow(SaleFlow saleFlow, JSONObject jsonObject) {
        ArrayList<SaleFlow> goodsList = Means.getInstance().getItemHead();
        try{
            for(SaleFlow item : goodsList){
                if(item.getBarcode().equals(saleFlow.getBarcode())){
                    saleFlow.setAmount(jsonObject.getDouble("amount"));
                    saleFlow.setDisc(100);
                    saleFlow.setDiscAmt(item.getDiscAmt());
                    saleFlow.setDisctype("");
                    saleFlow.setErpLinenmbr(item.getErpLinenmbr());
                    saleFlow.setExpectweight(item.getExpectweight());
                    saleFlow.setFlowid(item.getFlowid());
                    saleFlow.setFname(item.getFname());
                    saleFlow.setIncode(item.getIncode());
                    saleFlow.setWeight(item.getWeight());
                    saleFlow.setPlutype(item.getPlutype());
                    saleFlow.setUnitprice(item.getUnitprice());
                    saleFlow.setQty(item.getQty());
                    saleFlow.setPrice(item.getPrice());
                    saleFlow.setWeightPluType(item.getWeightPluType());
                    if(!saleFlow.getPlutype().equals("3")){
                        saleFlow.setCount(1);
                    }
                    saleFlow.setSpecs("");
                    saleFlow.setUnit("");
                    return;
                }
            }
            saleFlow.setAmount(jsonObject.getDouble("amount"));
            saleFlow.setDisc(100);
            saleFlow.setDiscAmt(jsonObject.getDouble("linedisc"));
            saleFlow.setDisctype("");
            saleFlow.setErpLinenmbr(jsonObject.getInt("linenmbr"));
            saleFlow.setExpectweight(jsonObject.getDouble("weight"));
            saleFlow.setFlowid(jsonObject.getInt("linenmbr"));
            saleFlow.setFname(jsonObject.getString("desc"));
            saleFlow.setIncode(jsonObject.getString("itemnmbr"));
            // TODO: 2018/7/24 商品类型
            String plutype = jsonObject.getString("plutype");//0-普通，1-称重，2-计数
            Double weight = jsonObject.getDouble("weight");
            Double qty = jsonObject.getDouble("qtysold");
            saleFlow.setWeight(weight);
            saleFlow.setQty(qty);
//            if (plutype.equals("1") && (weight == 1.000 || weight == 1000)) {
//                saleFlow.setPlutype("2");
//            } else {
                saleFlow.setPlutype(plutype);
//            }
            saleFlow.setUnitprice(jsonObject.getDouble("unitprice"));
            saleFlow.setQty(jsonObject.getDouble("qtysold"));
            if(saleFlow.getPlutype().equals("0")){
                saleFlow.setPrice(saleFlow.getAmount());
            }else {
                if(saleFlow.getWeightPluType() == 2){
                    saleFlow.setPrice(saleFlow.getAmount());
                }else {
                    saleFlow.setPrice(saleFlow.getAmount());
                }
            }
            if(!saleFlow.getPlutype().equals("3")){
                saleFlow.setCount(1);
            }
            saleFlow.setSpecs("");
            saleFlow.setUnit("");
            LogUtils.e("*********************" + "add getWeightPluType" + getWeightPluType1(saleFlow.getBarcode(), saleFlow.getWeight(), saleFlow.getPlutype(), saleFlow.getQty()));
            saleFlow.setWeightPluType(getWeightPluType1(saleFlow.getBarcode(), saleFlow.getWeight(), saleFlow.getPlutype(), saleFlow.getQty()));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private int getWeightPluType1(String barcode, double weight, String plutype, double qty) {
        int type = Integer.valueOf(plutype);
//        if(type == 1 && (weight == 1.000*qty || weight == 0.001*qty)){
//            type = 2;
//        }
//        return type;
//        boolean result = false;
        String code = barcode.replaceAll("^[a-zA-Z]", "");
        if((code.length() == 18) || (code.length() == 24)){
            String shortCode = code.substring(6, 12);
            LogUtils.e("short Code" + shortCode);
            if(((Integer.valueOf(shortCode)%1000) == 0) || shortCode.equals("000001")){
                type = 2;
            }
        }
        return type;
    }


    //判断商品重量
    private void scanPluVerify(SaleFlow saleFlow, double qty) {
        if(!Means.blScaleOK){
            return;
        }
        if(saleFlow.getPlutype().equals("3")){
            return;
        }
        isVerify = true;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                List<GoodsWeight> goodsWeightList = new ArrayList<GoodsWeight>();//与该商品有关的重量链表
                GoodsWeight goodsWeightItem = new GoodsWeight();//检索一个合法重量，当本次商品重量不在合法范围时以此为依据
                boolean blWeightExist = false;

                boolean blQtyPrice = false;        //是否数量价格发生变化，需要刷整单
                boolean blScalePLU = false;        //判断是否称重商品

                double tmpExpectWeight = 0;    //预期重量：称重商品从erp获取换算的重量；普通商品从已合法的重量列表中取一个；
                double tmpExpectTolerance = Means.ToleranceDefault; //预期重量误差：称重商品默认ToleranceWeightPLU对应值；普通商品从已合法的重量列表中取一个；
                double tmpWeight = 0; //秤上添加的重量
                double tmpTolerance = 0;//添加的重量误差

                goodsWeightList = GoodsHelper.GetApprovedWeight(mGoodsWeightDao, saleFlow.getBarcode(), saleFlow.getIncode());
                LogUtils.d("------>good dao weight" + saleFlow.getBarcode() + "--" + goodsWeightList.size() + "run: goodsWeightList.size()"+ goodsWeightList.size(), true);
                goodsWeightItem = null;//重量检测中以goodsWeightList为准, 检索不到合法重量时以此为依据
                if (goodsWeightList != null && goodsWeightList.size() > 0) {
                    for (int i = 0; i < goodsWeightList.size(); i++) {
                        GoodsWeight item = goodsWeightList.get(i);
                        if (item.getApprovedflag().equals("1") && item.getWeight() > 0) {
                            if (item.getQty() == 1) {
                                goodsWeightItem = item;
                                break;
                            } else {
                                goodsWeightItem = item;
                            }
                        }
                    }
                    //设定预期重量及误差
                    if (goodsWeightItem != null) {
                        tmpExpectWeight = goodsWeightItem.getWeight();
                        if(saleFlow.getPlutype().equals("0")){
                            tmpExpectWeight = tmpExpectWeight* qty;
                            LogUtils.d("-----tmpExpectWeight" + tmpExpectWeight, true);
                        }
                        if (goodsWeightItem.getDeviationtype() == 0 && goodsWeightItem.getAbs_deviation() > 0) {
                            //绝对误差
                            tmpExpectTolerance = goodsWeightItem.getAbs_deviation();
                        } else if (goodsWeightItem.getDeviationtype() == 1 && goodsWeightItem.getWeight() * goodsWeightItem.getPer_deviation() > 0) {
                            //百分比误差
                            tmpExpectTolerance = BigDecimal.valueOf(goodsWeightItem.getWeight()).multiply(BigDecimal.valueOf(goodsWeightItem.getPer_deviation())).doubleValue();
                        } else {
                            //这里要根据数据库里的商品的实际重量再次判定.
                            if (tmpExpectWeight < Means.WeightStep1){
                                tmpExpectTolerance = Means.ToleranceAbsStep1;
                            }else if (tmpExpectWeight>=Means.WeightStep1 && tmpExpectWeight < Means.WeightStep2){
                                tmpExpectTolerance = tmpExpectWeight * Means.ToleranceRateStep2;
                            }else{
                                tmpExpectTolerance = Means.ToleranceDefault;//默认误差
                            }
                        }
                        tmpExpectTolerance = tmpExpectTolerance*qty;
                    }
                }

                //将称重商品erp返回的重量增加到重量列表，统一判断
                //称重商品，POS系统返回计算重量,设定预期重量及误差
                //称重商品意外干预超过3次，当日不再干预;增加为零重量商品
                //计件商品不严格判断重量
                if (saleFlow.getPlutype().equals("1")) {
                    //计重商品
                    int count = 0;//当日干预次数
                    count = GoodsHelper.SelectItemException(mItemExceptionsDao, saleFlow.getBarcode(), saleFlow.getIncode());
                    LogUtils.d(TAG + "run: count:" + count, true);
                    //获取计重商品的重量和误差
                    blScalePLU = true;
                    tmpExpectWeight = saleFlow.getWeight();//ERP返回称重商品重量
                    tmpExpectTolerance = Means.ToleranceWeightPLU;//称重商品误差

                    //将称重商品重量增加到重量列表，统一判断
                    GoodsWeight tmp = new GoodsWeight();
                    tmp.setId("");
                    tmp.setBarcode(saleFlow.getBarcode());
                    tmp.setQty(1);
                    if (count > 3) {
                        tmp.setWeight(0.00);
                    }else if (saleFlow.getWeightPluType()==2){
                        tmp.setWeight(0.00);
                    } else{
                        tmp.setWeight(saleFlow.getWeight());
                    }
                    tmp.setApprovedflag("1");
                    tmp.setDeviationtype(0);
                    tmp.setAbs_deviation(tmpExpectTolerance);
                    tmp.setPer_deviation(0.00);
                    tmp.setGoodsattr("000");
                    tmp.setRestype(0);
                    tmp.setSubcode("");
                    tmp.setExpirydays(0);
                    tmp.setRemark("");
                    tmp.setState("0");
                    tmp.setUpdate_name("");
                    Date date = new Date();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                    tmp.setUpdate_date(simpleDateFormat.format(date));
                    tmp.setUpdate_by("");
                    tmp.setCreate_name("");
                    tmp.setCreate_date(simpleDateFormat.format(date));
                    tmp.setCreate_by("");
                    tmp.setPlutype("1");  //称重商品标志
                    goodsWeightList.add(tmp);
                    goodsWeightItem = tmp;
                } else if (saleFlow.getPlutype().equals("2")) {
                    //计件商品不严格验证重量
                    GoodsWeight tmp = new GoodsWeight();
                    tmp.setId("");
                    tmp.setBarcode(saleFlow.getBarcode());
                    tmp.setQty(1);
                    tmp.setWeight(0.00);
                    tmp.setApprovedflag("1");
                    tmp.setDeviationtype(0);
                    tmp.setAbs_deviation(0.00);
                    tmp.setPer_deviation(0.00);
                    tmp.setGoodsattr("000");
                    tmp.setRestype(0);
                    tmp.setSubcode("");
                    tmp.setExpirydays(0);
                    tmp.setRemark("");
                    tmp.setState("0");
                    tmp.setUpdate_name("");
                    Date date = new Date();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                    tmp.setUpdate_date(simpleDateFormat.format(date));
                    tmp.setUpdate_by("");
                    tmp.setCreate_name("");
                    tmp.setCreate_date(simpleDateFormat.format(date));
                    tmp.setCreate_by("");
                    tmp.setPlutype("0");
                    goodsWeightList.add(tmp);
                }

                //添加商品实际重量，重量未变化时延时1秒
                tmpWeight = BigDecimal.valueOf(Means.weightqty).subtract(BigDecimal.valueOf(Means.TotalWeight)).doubleValue();
                if (tmpWeight < Means.ToleranceScanSmall)
                {
                    int iCount = 0;
                    while (iCount < 2 && tmpWeight <= Means.ToleranceScanSmall)
                    {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        iCount++;
                        tmpWeight = BigDecimal.valueOf(Means.weightqty).subtract(BigDecimal.valueOf(Means.TotalWeight)).doubleValue();
                    }
                }
                Means.blApproveWeight = false;

                while (isVerify) {
                    LogUtils.d("garlic" + "继续执行增加商品重量处理逻辑", false);
                    try {
                        Thread.sleep(50);
                        tmpWeight = BigDecimal.valueOf(Means.weightqty).subtract(BigDecimal.valueOf(Means.TotalWeight)).doubleValue();
                        if (tmpWeight <= Means.ToleranceScanSmall)
                        {
                            Thread.sleep(500);
                            tmpWeight = BigDecimal.valueOf(Means.weightqty).subtract(BigDecimal.valueOf(Means.TotalWeight)).doubleValue();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (Means.blApproveWeight) {
                        //员工确认重量，不再判断商品库重量信息
                        LogUtils.d("weight1111111: weightqty:" + Means.weightqty + "Means.TotalWeight:" + Means.TotalWeight + "weightExcept:" + tmpExpectWeight + "weightExpectTolerance" + tmpExpectTolerance, true);
                        if (saleFlow.getPlutype().equals("0") && tmpWeight > Means.TolerancePrecision) {
                            //普通商品自学习重量
                            LearnGoodsWeight(saleFlow.getBarcode(), tmpWeight);
                        }
                        //更新链表信息
                        TradeHelper.UpdateItem(saleFlow.getBarcode(), saleFlow.getFlowid(), tmpWeight/qty);
                        //Means.blApproveWeight = false;
                        isVerify = false;
                        Means.TotalWeight = Means.weightqty;
                        Message message = Message.obtain();
                        message.what = 3;
                        handler.sendMessage(message);
                        break;
                    } else {


                        if (tmpWeight <= 0) {
                            //未检测到重量，启动装袋提示
                            if(!isWeighting){
                                //重量窗口未显示，启动装袋提示
                                Message message = Message.obtain();
                                message.what = 1;
                                message.obj = JLFConstant.WEIGHT_BAG_DLG;
                                handler.sendMessage(message);
                                LogUtils.d("weight222222222: weightqty:" + Means.weightqty + "Means.TotalWeight:" + Means.TotalWeight + "weightExcept:" + tmpExpectWeight + "weightExpectTolerance" + tmpExpectTolerance, true);
                            }
                            else{
                                //重量窗口已显示，改变窗口提示内容
                                Message message = Message.obtain();
                                message.what = 2;
                                message.obj = JLFConstant.WEIGHT_BAG_DLG;
                                handler.sendMessage(message);
                            }
                        } else {
                            //检测到重量变化，判断重量合法性
                            if (goodsWeightList != null && goodsWeightList.size() > 0) {
                                //遍历重量列表，检测是否有符合重量
                                for (int i = 0; i < goodsWeightList.size(); i++) {
                                    GoodsWeight item = goodsWeightList.get(i);
                                    if (item.getApprovedflag().equals("1")) {
                                        if (item.getDeviationtype() == 0 && item.getWeight() > 0) {
                                            tmpTolerance = item.getAbs_deviation();
                                        } else if (item.getDeviationtype() == 1 && item.getWeight() * item.getPer_deviation() > 0) {
                                            tmpTolerance = BigDecimal.valueOf(item.getWeight()).multiply(BigDecimal.valueOf(item.getPer_deviation())).doubleValue();
                                        } else {
                                            tmpTolerance = Means.ToleranceDefault;
                                        }
                                        //重量在允许范围
                                        if (tmpWeight <= BigDecimal.valueOf(item.getWeight()).add(BigDecimal.valueOf(tmpTolerance)).doubleValue()*qty && tmpWeight >=BigDecimal.valueOf(item.getWeight()).subtract(BigDecimal.valueOf(tmpTolerance)).doubleValue()*qty
                                                || (item.getWeight() == 0 && tmpWeight > Means.ToleranceNoScan)) {
                                            //商品重量在误差范围之内...或者 ...商品的重量为0.同时称台上一级添加了额重量了..
                                            Message message = Message.obtain();
                                            message.what = 4;
                                            handler.sendMessage(message);
                                            blWeightExist = true;
                                            isVerify = false;
                                            //更新链表重量信息
                                            LogUtils.d("tmpwieght = " + tmpWeight + " : qty="+qty, true);
                                            TradeHelper.UpdateItem(saleFlow.getBarcode(), saleFlow.getFlowid(), tmpWeight/qty);
                                            Means.TotalWeight = Means.weightqty;
                                            LogUtils.d("tmpWeight:"+tmpWeight+ "  item.getWeight():"+item.getWeight() + "  tmpTolerance:"+tmpTolerance, true);
                                            LogUtils.d("weight333333333: weightqty:" + Means.weightqty + "Means.TotalWeight:" + Means.TotalWeight + "tmpweight:" + tmpWeight + "item.getDoubleWeight()" + item.getWeight() + "tmptolerance:" + tmpTolerance, true);
                                            break;
                                        }
                                    }
                                }
                                if (blWeightExist) {
                                    LogUtils.d("weight4444444444: weightqty:" + Means.weightqty + "Means.TotalWeight:" + Means.TotalWeight + "weightExcept:" + tmpExpectWeight + "weightExpectTolerance" + tmpExpectTolerance, true);
                                    Message message = Message.obtain();
                                    message.what = 4;
                                    handler.sendMessage(message);
                                    isVerify = false;
                                    Means.blApproveWeight = false;
                                    break;
                                } else {
                                    LogUtils.d("garlic: tmpWeight="+tmpWeight,false);
                                    LogUtils.d("garlic: tmpWeight1="+BigDecimal.valueOf(tmpExpectWeight).subtract(BigDecimal.valueOf(tmpExpectTolerance)).doubleValue(),false);
                                    LogUtils.d("garlic: tmpWeight2="+BigDecimal.valueOf(tmpExpectWeight).add(BigDecimal.valueOf(tmpExpectTolerance)).doubleValue(),false);
                                    //未找到认可重量
                                    //以goodsweightitem为标准判断提示“装袋”窗口或“协助”窗口
                                    if (goodsWeightItem != null && goodsWeightItem.getBarcode() != null && !goodsWeightItem.getBarcode().isEmpty()) {
                                        if (tmpWeight < BigDecimal.valueOf(tmpExpectWeight).subtract(BigDecimal.valueOf(tmpExpectTolerance)).doubleValue() ) {
                                            //重量小于误差范围下限,启动装袋提示
                                            if(!isWeighting){
                                                Message message = Message.obtain();
                                                message.what = 1;
                                                message.obj = JLFConstant.WEIGHT_LOW_DLG;
                                                handler.sendMessage(message);
                                                LogUtils.d("weight555555555: weightqty:" + Means.weightqty + "Means.TotalWeight:" + Means.TotalWeight + "weightExcept:" + tmpExpectWeight + "weightExpectTolerance" + tmpExpectTolerance, true);
                                            }
                                            else {
                                                Message message = Message.obtain();
                                                message.what = 2;
                                                message.obj = JLFConstant.WEIGHT_LOW_DLG;
                                                handler.sendMessage(message);
                                            }
                                        } else if (tmpWeight > BigDecimal.valueOf(tmpExpectWeight).add(BigDecimal.valueOf(tmpExpectTolerance)).doubleValue()) {
                                            //重量大于误差范围上限,启动协助提示
                                            if(!isWeighting){
                                                Message message = Message.obtain();
                                                message.what = 1;
                                                message.obj = JLFConstant.WEIGHT_OVER_DLG;
                                                handler.sendMessage(message);
                                                LogUtils.d("weight6666666666: weightqty:" + Means.weightqty + "Means.TotalWeight:" + Means.TotalWeight + "weightExcept:" + tmpExpectWeight + "weightExpectTolerance" + tmpExpectTolerance, true);
                                            }
                                            else {
                                                Message message = Message.obtain();
                                                message.what = 2;
                                                message.obj = JLFConstant.WEIGHT_OVER_DLG;
                                                handler.sendMessage(message);
                                                //weightDialog.setContent(JLFConstant.WEIGHT_OVER_DLG);
                                            }
                                        } else {
                                            //重量在允许范围,结束比较
                                            if (saleFlow.getPlutype().equals("0") && tmpWeight > Means.TolerancePrecision) {
                                                //普通商品 保存重量
                                                LearnGoodsWeight(saleFlow.getBarcode(), tmpWeight);
                                            }
                                            //更新链表重量信息
                                            blWeightExist = true;
                                            isVerify = false;
                                            TradeHelper.UpdateItem(saleFlow.getBarcode(), saleFlow.getFlowid(), tmpWeight/qty);
                                            LogUtils.d("weight7777777777: weightqty:" + Means.weightqty + "Means.TotalWeight:" + Means.TotalWeight + "weightExcept:" + tmpExpectWeight + "weightExpectTolerance" + tmpExpectTolerance, true);
                                            Message message = Message.obtain();
                                            message.what = 4;
                                            handler.sendMessage(message);
                                            Means.blApproveWeight = false;
                                            break;
                                        }
                                    } else {
                                        //无标准商品，普通商品自学习重量,结束比较
                                        if (saleFlow.getPlutype().equals("0") && tmpWeight > Means.TolerancePrecision) {
                                            //普通商品 保存重量
                                            LearnGoodsWeight(saleFlow.getBarcode(), tmpWeight);
                                        }
                                        //更新链表重量信息
                                        blWeightExist = true;
                                        isVerify = false;
                                        TradeHelper.UpdateItem(saleFlow.getBarcode(), saleFlow.getFlowid(), tmpWeight/qty);
                                        LogUtils.d("weight8888888: weightqty:" + Means.weightqty + "Means.TotalWeight:" + Means.TotalWeight + "weightExcept:" + tmpExpectWeight + "weightExpectTolerance" + tmpExpectTolerance, true);
                                        Message message = Message.obtain();
                                        message.what = 4;
                                        handler.sendMessage(message);
                                        Means.blApproveWeight = false;
                                        break;
                                    }
                                }
                            } else {
                                //无标准商品，普通商品自学习重量,结束比较
                                if (saleFlow.getPlutype().equals("0") && tmpWeight > Means.TolerancePrecision) {
                                    LogUtils.d(TAG + "run: LearnGoodsWeight", true);
                                    //普通商品 保存重量
                                    LearnGoodsWeight(saleFlow.getBarcode(), tmpWeight);
                                }
                                //更新链表重量信息
                                blWeightExist = true;
                                isVerify = false;
                                TradeHelper.UpdateItem(saleFlow.getBarcode(), saleFlow.getFlowid(), tmpWeight/qty);
                                LogUtils.d("weight99999999: weightqty:" + Means.weightqty + "Means.TotalWeight:" + Means.TotalWeight + "weightExcept:" + tmpExpectWeight + "weightExpectTolerance" + tmpExpectTolerance, true);
                                Message message = Message.obtain();
                                message.what = 4;
                                handler.sendMessage(message);
                                Means.blApproveWeight = false;
                                break;
                            }
                        }
                    }
                }
            }
        };
        executorService.execute(runnable);
    }

    public void serWeighting(boolean b) {
            isWeighting = true;
    }

    public void processCount(int i) {
        SaleFlow saleFlow = Means.getInstance().getItemHead().get(i - 1);
        //SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        int count1 = mItemExceptionsDao.queryBuilder().whereOr(ItemExceptionsDao.Properties.Barcode.eq(saleFlow.getBarcode()), ItemExceptionsDao.Properties.Incode.eq(saleFlow.getIncode())).list().size();
        int count = GoodsHelper.SelectItemException(mItemExceptionsDao, saleFlow.getBarcode(), saleFlow.getIncode());
        LogUtils.d("twoOk: count1:" + count1 + "count:" + count, true);
        if(count > 3){
            GoodsHelper.UpdateApprovedWeight(mGoodsWeightDao ,saleFlow.getBarcode());
        }
    }

    /*
    自学习重量
     */
    private void LearnGoodsWeight(String barcode, double weight) {
        GoodsWeight item = new GoodsWeight();
        item.setId(Means.getInstance().GetGuid());
        item.setBarcode(barcode);
        item.setQty(1);
        item.setWeight(weight);
        item.setApprovedflag("0");
        if (weight < Means.WeightStep1) {
            item.setDeviationtype(0);
            item.setAbs_deviation(Means.ToleranceAbsStep1);
            item.setPer_deviation(0.00);
        } else if (weight >= Means.WeightStep1 && weight < Means.WeightStep2) {
            item.setDeviationtype(1);
            item.setAbs_deviation(0.00);
            item.setPer_deviation(Means.ToleranceRateStep2);
        } else {
            item.setDeviationtype(0);
            item.setAbs_deviation(Means.ToleranceDefault);
            item.setPer_deviation(0.00);
        }
        item.setGoodsattr("000");
        item.setRestype(0);
        item.setExpirydays(0);
        item.setRemark("AUTO");
        item.setSubcode("");
        item.setState("0");
        item.setUpdate_name(Means.getInstance().getLoginCashier());

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        item.setUpdate_date(simpleDateFormat.format(date));
        item.setUpdate_by(Means.getInstance().getLoginCashier());
        item.setCreate_name(Means.getInstance().getLoginCashier());
        item.setCreate_date(simpleDateFormat.format(date));
        item.setCreate_by(Means.getInstance().getLoginCashier());
        item.setPlutype("0");
        //保存重量
        GoodsHelper.LearnGoodsWeight(mGoodsWeightDao ,item);
    }

    public void shutDownThread() {
        if (!executorService.isShutdown()){
            executorService.shutdownNow();
        }
    }

    public void processNor(String operateId) {
        int i = Means.getInstance().getItemHead().size();
        if(i > 0){
            SaleFlow saleFlow = Means.getInstance().getItemHead().get(i - 1);
            double tmpweight = (BigDecimal.valueOf(Means.weightqty).subtract(BigDecimal.valueOf(Means.TotalWeight))).doubleValue();
            //登记商品意外干预日志
            ItemExceptions item = new ItemExceptions();
            item.setId(Means.getInstance().GetGuid());
            item.setIncode(saleFlow.getIncode());
            item.setBarcode(saleFlow.getBarcode());
            item.setFname(saleFlow.getFname());
            item.setExpectedweight(0);
            item.setObservedweight(tmpweight);
            item.setExceptiontype(0);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            item.setEntrytime(simpleDateFormat.format(new Date()));
            item.setFlowno(Means.getInstance().getRec_Tran().getTransnmbr());
            item.setPoscode(Means.getInstance().getPosno());
            item.setPoscaseid(Means.getInstance().getPosno());
            item.setCustid("");
            item.setOrgid("");
            item.setOperatorid(operateId);
            GoodsHelper.SaveItemException(mItemExceptionsDao, item);

            int count = GoodsHelper.SelectItemException(mItemExceptionsDao, saleFlow.getBarcode(), saleFlow.getIncode());
            LogUtils.d("twoOk:count:" + count, true);
            if(count > 3){
                GoodsHelper.UpdateApprovedWeight(mGoodsWeightDao ,saleFlow.getBarcode());
            }
        }
    }

    public void setIsVerify(boolean isVerify) {
        this.isVerify = isVerify;
    }

    public void setIsCancelling(boolean isCancelling){
        this.isCancelling = isCancelling;
    }
}
